import cn.igroup.service.push.proto.PushMsgOuterClass;
import idle.ConnectionWatcher;
import idle.ConnectorIdleStateTrigger;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author LONG
 * @date 2018/1/8 15:35
 */
public class ClientBootstrap {

    private final ConnectorIdleStateTrigger idleStateTrigger = new ConnectorIdleStateTrigger();
    private final EventLoopGroup group = new NioEventLoopGroup(2);
    static final String host = "192.168.2.135";
    static int port = 8000;
    private Bootstrap bootstrap = new Bootstrap();
    private Channel channel;

    //static Scanner scanner = new Scanner(System.in);

    public void connect() throws Exception {
        // Configure the client.
        //禁用nagle算法
        bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
        final ConnectionWatcher watcher = new ConnectionWatcher(bootstrap, host, port, true) {
            @Override
            public ChannelHandler[] handlers() {
                return new ChannelHandler[]{
                        new IdleStateHandler(0, 20, 0, TimeUnit.SECONDS),
                        idleStateTrigger,
                        new ProtobufVarint32FrameDecoder(),
                        new ProtobufDecoder(PushMsgOuterClass.PushMsg.getDefaultInstance()),
                        new ProtobufVarint32LengthFieldPrepender(),
                        new ProtobufEncoder(),
//                        new LengthFieldBasedFrameDecoder(1024, 0, 2, 0, 2),
//                        this,
//                        new IdleStateHandler(0, 20, 0, TimeUnit.SECONDS),
//                        idleStateTrigger,
//                        new StringDecoder(),
//                        new LengthFieldPrepender(2),
//                        new StringEncoder(),
                        new ClientHandler()
                };
            }
        };

        ChannelFuture future = null;
        //进行连接
        try {
            synchronized (bootstrap) {
                bootstrap.handler(new ChannelInitializer<Channel>() {
                    //初始化channel
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(watcher.handlers());
                    }
                });
                future = bootstrap.connect(host, port);
                future.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture futureListener) throws Exception {
                        if (futureListener.isSuccess()) {
                            channel = futureListener.channel();
                            System.out.println("Connect to server successfully!");
                        } else {
                            System.out.println("Failed to connect to server, try connect after 10s");
                            futureListener.channel().eventLoop().schedule(new Runnable() {
                                @Override
                                public void run() {
                                    doConnect(host, port);
                                }
                            }, 10, TimeUnit.SECONDS);
                        }
                    }
                });
            }
            // 以下代码在synchronized同步块外面是安全的
            future.sync();
        } catch (Throwable t) {
            throw new Exception("connects to  fails", t);
        }

    }

    protected void doConnect(String host, int port) {
        if (channel != null && channel.isActive()) {
            return;
        }
        ChannelFuture future = bootstrap.connect(host, port);
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture futureListener) throws Exception {
                if (futureListener.isSuccess()) {
                    System.out.println("Connect to server successfully!");
                    channel = futureListener.channel();
                } else {
                    System.out.println("Failed to connect to server, try connect after 10s");
                    futureListener.channel().eventLoop().schedule(new Runnable() {
                        @Override
                        public void run() {
                            doConnect(host, port);
                        }
                    }, 10, TimeUnit.SECONDS);
                }
            }
        });
    }

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        if (args != null && args.length > 0) {
            try {
                port = Integer.valueOf(args[0]);
            } catch (NumberFormatException e) {
                // 采用默认值
            }
        }
        new ClientBootstrap().connect();
    }
}
